import datetime

import json
from tornado.web import RequestHandler
import tornado.gen
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
from bot.enterprise_wechat_gpt.config.conf import *
from bot.enterprise_wechat_gpt.util.user_util import get_all_week_user
from bot.enterprise_wechat_gpt.util.user_info_util import set_user_info, get_user_info_dict, check_coupon
from bot.enterprise_wechat_gpt.util.id_distributor import get_all_ab_user


class RedisHandler(RequestHandler):

    executor = ThreadPoolExecutor(8)

    @tornado.gen.coroutine
    def get(self, path):
        output = yield self.handler_get(path)
        self.write(str(output))

    @run_on_executor
    def handler_get(self, path):
        match path:
            case 'get_week_user_Ids':
                output = get_all_week_user()
            case 'get_all_ab_user':
                date = self.get_argument("date", datetime.datetime.now().strftime("%Y-%m-%d"))
                output = get_all_ab_user(date)
            case 'get_user_info':
                wx_id = self.get_argument("wxId", None)
                if wx_id is None:
                    output = 'wxId不能为空！'
                else:
                    user_info = get_user_info_dict(wx_id)
                    output = user_info.get("json_data")
                    logging.info(f"获取用户信息 wxId:{wx_id} userInfo:{output}")
            case _:
                logging.warning(f"/redis/{path} 没有该路径!")
                output = '没有该路径！'
        return output

    @tornado.gen.coroutine
    def post(self, path):
        yield self.handler_post(path)

    @run_on_executor
    def handler_post(self, path):
        match path:
            case 'set_user_info':
                body = self.request.body.decode("utf-8")
                user_info = json.loads(body)
                customer_id = self.get_argument("customerId", None)
                wx_id = self.get_argument("wxId", None)
                agent_id = self.get_argument("agent_id", None)
                logging.info(f"/redis/set_user_info?customerId={customer_id}&wxId={wx_id}&agent_id={agent_id}  body:{user_info}")
                # set_user_info(wx_id, json.dumps(user_info, ensure_ascii=False, indent=2))
                set_user_info(customer_id, wx_id, agent_id, user_info)
                check_coupon(user_info)
                self.write("ok")
